<template>
  <div class="container">
    <header>
      <h1>Vue 2 + ECharts 柱状图</h1>
      <p class="subtitle">Vue.js (2.6.12) + ECharts (5.4.0)</p>
    </header>
    
    <div class="controls">
      <button 
        class="btn" 
        :class="{active: chartType === 'basic'}" 
        @click="changeChartType('basic')"
      >
        <i class="fas fa-chart-bar"></i> 基础柱状图
      </button>
      <button 
        class="btn" 
        :class="{active: chartType === 'stacked'}" 
        @click="changeChartType('stacked')"
      >
        <i class="fas fa-layer-group"></i> 堆叠柱状图
      </button>
      <button 
        class="btn" 
        :class="{active: chartType === 'horizontal'}" 
        @click="changeChartType('horizontal')"
      >
        <i class="fas fa-bars"></i> 水平柱状图
      </button>
    </div>
    
    <div class="charts-container">
      <!-- 主图表 -->
      <div class="chart-card">
        <div class="chart-header">
          <div class="chart-icon">
            <i class="fas fa-chart-bar"></i>
          </div>
          <h2 class="chart-title">{{ getChartTitle() }}</h2>
        </div>
        <div class="chart-wrapper" ref="mainChart"></div>
        
        <div class="data-controls">
          <h3>数据控制</h3>
          <div class="control-group">
            <label>
              数据量: {{ dataCount }}
              <span class="range-value">{{ dataCount }}</span>
            </label>
            <input type="range" min="5" max="12" v-model="dataCount" @input="updateChartData">
          </div>
          
          <div class="control-group">
            <label>
              最大值: {{ maxValue }}
              <span class="range-value">{{ maxValue }}</span>
            </label>
            <input type="range" min="100" max="1000" step="100" v-model="maxValue" @input="updateChartData">
          </div>
          
          <button class="btn" @click="generateRandomData">
            <i class="fas fa-random"></i> 生成随机数据
          </button>
        </div>
      </div>
      
      <!-- 数据表格 -->
      <div class="chart-card">
        <div class="chart-header">
          <div class="chart-icon">
            <i class="fas fa-table"></i>
          </div>
          <h2 class="chart-title">数据表格</h2>
        </div>
        
        <table class="data-table">
          <thead>
            <tr>
              <th>月份</th>
              <th>销售额</th>
              <th>同比增长</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) in chartData" :key="index">
              <td>{{ item.name }}</td>
              <td>{{ item.value }}</td>
              <td>{{ calculateGrowth(item.value, index) }}%</td>
            </tr>
          </tbody>
        </table>
        
        <div class="data-controls">
          <h3>图表信息</h3>
          <p><strong>图表类型:</strong> {{ getChartTitle() }}</p>
          <p><strong>数据总量:</strong> {{ totalValue }} 单位</p>
          <p><strong>平均值:</strong> {{ averageValue }} 单位</p>
          <p><strong>最大值:</strong> {{ maxDataValue }} 单位</p>
        </div>
      </div>
    </div>
    
    <footer>
      <p>Vue 2 + ECharts 柱状图示例</p>
    </footer>
  </div>
</template>

<script>
// 引入ECharts
import * as echarts from 'echarts';

export default {
  name: 'BarChartDemo',
  
  data() {
    return {
      chartType: 'basic',
      dataCount: 7,
      maxValue: 500,
      chartData: [],
      mainChartInstance: null
    }
  },
  
  computed: {
    // 计算总数值
    totalValue() {
      return this.chartData.reduce((sum, item) => sum + item.value, 0);
    },
    
    // 计算平均值
    averageValue() {
      return this.chartData.length ? Math.round(this.totalValue / this.chartData.length) : 0;
    },
    
    // 找出最大值
    maxDataValue() {
      return this.chartData.length ? Math.max(...this.chartData.map(item => item.value)) : 0;
    }
  },
  
  methods: {
    // 生成随机数据
    generateData() {
      const categories = ['一月', '二月', '三月', '四月', '五月', '六月', 
                        '七月', '八月', '九月', '十月', '十一月', '十二月'];
      const data = [];
      
      for (let i = 0; i < this.dataCount; i++) {
        const category = i < categories.length ? categories[i] : `类别${i+1}`;
        data.push({
          name: category,
          value: Math.floor(Math.random() * this.maxValue) + 50
        });
      }
      
      return data;
    },
    
    // 更新图表数据
    updateChartData() {
      this.chartData = this.generateData();
      this.initMainChart();
    },
    
    // 生成随机数据
    generateRandomData() {
      this.chartData = this.generateData();
      this.initMainChart();
    },
    
    // 更改图表类型
    changeChartType(type) {
      this.chartType = type;
      this.initMainChart();
    },
    
    // 获取图表标题
    getChartTitle() {
      const titles = {
        'basic': '基础柱状图',
        'stacked': '堆叠柱状图',
        'horizontal': '水平柱状图'
      };
      return titles[this.chartType] || '柱状图';
    },
    
    // 计算同比增长
    calculateGrowth(value, index) {
      if (index === 0) return '-';
      const prevValue = this.chartData[index - 1].value;
      const growth = ((value - prevValue) / prevValue * 100).toFixed(1);
      return growth;
    },
    
    // 初始化主图表
    initMainChart() {
      if (!this.$refs.mainChart) return;
      
      // 销毁现有实例
      if (this.mainChartInstance) {
        this.mainChartInstance.dispose();
      }
      
      // 创建新实例
      this.mainChartInstance = echarts.init(this.$refs.mainChart);
      
      // 准备数据
      const categories = this.chartData.map(item => item.name);
      const values = this.chartData.map(item => item.value);
      
      // 根据图表类型设置不同的配置
      let option = {};
      
      switch (this.chartType) {
        case 'basic':
          option = {
            title: {
              text: '月度销售数据',
              left: 'center',
              textStyle: {
                fontSize: 18,
                fontWeight: 'bold'
              }
            },
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'shadow'
              },
              formatter: '{b}: {c} 单位'
            },
            grid: {
              left: '3%',
              right: '4%',
              bottom: '3%',
              containLabel: true
            },
            xAxis: {
              type: 'category',
              data: categories,
              axisLabel: {
                rotate: 30
              }
            },
            yAxis: {
              type: 'value',
              name: '销售额',
              nameTextStyle: {
                padding: [0, 30, 0, 0]
              }
            },
            series: [{
              name: '销售额',
              type: 'bar',
              data: values,
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#83bff6' },
                  { offset: 0.5, color: '#188df0' },
                  { offset: 1, color: '#188df0' }
                ])
              },
              emphasis: {
                itemStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: '#2378f7' },
                    { offset: 0.7, color: '#2378f7' },
                    { offset: 1, color: '#83bff6' }
                  ])
                }
              },
              label: {
                show: true,
                position: 'top',
                formatter: '{c}'
              }
            }]
          };
          break;
          
        case 'stacked':
          // 生成堆叠数据
          const seriesData1 = values.map(v => Math.floor(v * 0.6));
          const seriesData2 = values.map(v => Math.floor(v * 0.4));
          
          option = {
            title: {
              text: '产品销售堆叠图',
              left: 'center',
              textStyle: {
                fontSize: 18,
                fontWeight: 'bold'
              }
            },
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'shadow'
              }
            },
            legend: {
              data: ['产品A', '产品B'],
              top: 30
            },
            grid: {
              left: '3%',
              right: '4%',
              bottom: '3%',
              containLabel: true
            },
            xAxis: {
              type: 'category',
              data: categories,
              axisLabel: {
                rotate: 30
              }
            },
            yAxis: {
              type: 'value',
              name: '销售额'
            },
            series: [
              {
                name: '产品A',
                type: 'bar',
                stack: '总量',
                data: seriesData1,
                itemStyle: {
                  color: '#5470c6'
                },
                label: {
                  show: true,
                  position: 'inside'
                }
              },
              {
                name: '产品B',
                type: 'bar',
                stack: '总量',
                data: seriesData2,
                itemStyle: {
                  color: '#91cc75'
                },
                label: {
                  show: true,
                  position: 'inside'
                }
              }
            ]
          };
          break;
          
        case 'horizontal':
          option = {
            title: {
              text: '月度销售数据对比',
              left: 'center',
              textStyle: {
                fontSize: 18,
                fontWeight: 'bold'
              }
            },
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'shadow'
              },
              formatter: '{b}: {c} 单位'
            },
            grid: {
              left: '3%',
              right: '4%',
              bottom: '3%',
              containLabel: true
            },
            xAxis: {
              type: 'value',
              name: '销售额'
            },
            yAxis: {
              type: 'category',
              data: categories,
              axisLabel: {
                interval: 0
              }
            },
            series: [{
              name: '销售额',
              type: 'bar',
              data: values,
              itemStyle: {
                color: (params) => {
                  // 使用函数返回颜色，实现不同颜色
                  const colorList = [
                    '#c23531', '#d48265', '#91c7ae', '#749f83', 
                    '#ca8622', '#bda29a', '#6e7074', '#546570',
                    '#61a0a8', '#d7504b', '#c6e579', '#f4e001'
                  ];
                  return colorList[params.dataIndex % colorList.length];
                }
              },
              label: {
                show: true,
                position: 'right',
                formatter: '{c}'
              }
            }]
          };
          break;
      }
      
      // 设置配置项并渲染图表
      this.mainChartInstance.setOption(option);
    },
    
    // 窗口调整大小处理
    handleResize() {
      if (this.mainChartInstance) {
        this.mainChartInstance.resize();
      }
    }
  },
  
  mounted() {
    // 初始化数据
    this.chartData = this.generateData();
    
    // 使用$nextTick确保DOM已经渲染
    this.$nextTick(() => {
      this.initMainChart();
    });
    
    // 监听窗口大小变化
    window.addEventListener('resize', this.handleResize);
  },
  
  beforeDestroy() {
    // 组件销毁时销毁图表实例
    if (this.mainChartInstance) {
      this.mainChartInstance.dispose();
      this.mainChartInstance = null;
    }
    
    // 移除事件监听
    window.removeEventListener('resize', this.handleResize);
  },
  
  watch: {
    // 监听数据变化
    chartData: {
      handler() {
        this.$nextTick(() => {
          if (this.mainChartInstance) {
            this.initMainChart();
          }
        });
      },
      deep: true
    }
  }
}
</script>

<style scoped>
.container {
  margin: 0 auto;
  padding: 20px;
  max-width: 1200px;
}

header {
  text-align: center;
  padding: 20px 0;
  margin-bottom: 30px;
}

h1 {
  font-size: 2.5rem;
  color: #3498db;
  margin-bottom: 10px;
}

.subtitle {
  font-size: 1.2rem;
  font-style: italic;
  color: #7f8c8d;
  max-width: 800px;
  margin: 0 auto;
}

.controls {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-bottom: 30px;
  flex-wrap: wrap;
}

.btn {
  background: #3498db;
  color: white;
  border: none;
  padding: 12px 20px;
  border-radius: 6px;
  cursor: pointer;
  font-weight: bold;
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  gap: 8px;
}

.btn:hover {
  background: #2980b9;
  transform: translateY(-2px);
}

.btn.active {
  background: #2c3e50;
}

.charts-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
  gap: 25px;
  margin-top: 30px;
}

.chart-card {
  background: white;
  border-radius: 10px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  padding: 25px;
  transition: transform 0.3s ease;
}

.chart-card:hover {
  transform: translateY(-5px);
}

.chart-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 2px solid #f1f1f1;
}

.chart-icon {
  width: 40px;
  height: 40px;
  background: #3498db;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  color: white;
  font-size: 1.2rem;
}

.chart-title {
  font-size: 1.3rem;
  color: #2c3e50;
}

.chart-wrapper {
  width: 100%;
  height: 400px;
  margin-top: 15px;
}

.data-controls {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  margin-top: 20px;
}

.control-group {
  margin-bottom: 15px;
}

label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
}

input[type="range"] {
  width: 100%;
}

.range-value {
  display: inline-block;
  min-width: 40px;
  text-align: center;
  background: #e9ecef;
  padding: 2px 8px;
  border-radius: 4px;
  font-weight: bold;
  margin-left: 10px;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
}

.data-table th, .data-table td {
  border: 1px solid #ddd;
  padding: 10px;
  text-align: center;
}

.data-table th {
  background-color: #f8f9fa;
  font-weight: 600;
}

.data-table tr:nth-child(even) {
  background-color: #f9f9f9;
}

footer {
  text-align: center;
  margin-top: 40px;
  color: #7f8c8d;
  font-size: 0.9rem;
}

@media (max-width: 768px) {
  .charts-container {
    grid-template-columns: 1fr;
  }
  
  .chart-wrapper {
    height: 300px;
  }
  
  .controls {
    flex-direction: column;
    align-items: center;
  }
  
  .btn {
    width: 200px;
  }
}
</style>